<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div style="margin-top: 15px;">

      </div>
      <el-row :gutter="20">
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <el-input @clear="getUserList" clearable v-model=queryInfo.query placeholder="请输入内容"
              class="input-with-select">
              <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="changeDialogVisible">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- table表单 -->
      <template>
        <el-table :data="userList" border stripe style="width: 100%">
          <el-table-column type="index" label="#">
          </el-table-column>
          <el-table-column prop="username" label="用户名">
          </el-table-column>
          <el-table-column prop="email" label="邮箱">
          </el-table-column>
          <el-table-column prop="mobile" label="电话">
          </el-table-column>
          <el-table-column prop="role_name" label="角色">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949"
                @change="userStateChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.id)"></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete"
                @click="deleteUserById(scope.row.id)"></el-button>
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button size="mini" type="warning" icon="el-icon-setting"
                  @click="settingRole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div class="block">

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size=queryInfo.pagesize
          layout="total, sizes, prev, pager, next, jumper" :total=total>
        </el-pagination>
      </div>
    </el-card>
    <!--添加用户 对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" :before-close="handleClose"
      @close="dialogVisibleClosed">

      <el-form ref="addFromRef" :rules="addFormRules" :model="addForm" class="add-form" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input prefix-icon="el-icon-user" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input prefix-icon="el-icon-folder-checked" v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input prefix-icon="el-icon-phone" v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户  对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" :before-close="handleClose"
      @close="editDialogClosed">
      <el-form ref="editFormRef" :rules="addFormRules" :model="editForm" class="add-form" label-width="80px">
        <el-form-item label="用户名">
          <el-input prefix-icon="iconfont icon-user" v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input prefix-icon="el-icon-folder-checked" v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input prefix-icon="el-icon-phone" v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="settingDialogVisible" width="50%" :before-close="handleClose"
      @close="settingDialogVisibleClosed">
      <div>
        <p>当前的用户是:{{ userInfo.username }}</p>
        <p>当前的角色是:{{ userInfo.role_name }}</p>
        <p>分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>

    </el-dialog>
  </div>

</template>

<script>

export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式  注意（/   /)加在两边才能用
      let regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        cb()
      } else {
        cb(new Error('请输入合法的邮箱'))
      }

    }
    const checkMobile = (rule, value, cb) => {
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }
    return {
      // 获取列表对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      editForm: {},
      settingForm: {},
      userInfo: {},
      roleList: [],
      total: 0,
      dialogVisible: false,
      editDialogVisible: false,
      deleteDialogVisible: false,
      settingDialogVisible: false,
      selectRoleId:'',
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',

      },
      addFormRules: {
        username: [
          { required: true, message: '请输入活动用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入角色类型', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],


      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChange(mg_state) {
      const { data: res } = await this.$http.put(`users/${mg_state.id}/state/${mg_state.mg_state}`)
      console.log(res);
      if (res.meta.status !== 200) {
        mg_state.mg_state = !mg_state.mg_state
        return this.$message.error('状态更新失败')
      }
      this.$message.success('状态更新成功')
      this.getUserList()
    },
    changeDialogVisible() {
      this.dialogVisible = true
    },
    dialogVisibleClosed() {
      this.$refs.addFromRef.resetFields()
    },
    addUser() {

      this.$refs.addFromRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 今天做到这了
    async editDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询用户信息失败')
      this.editForm = res.data

    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {

      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error("表单验证失败")
        // this.$message.success("表单验证成功")
        // this.editDialog()
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error("修改用户信息失败")
        this.editDialogVisible = false
        this.$message.success('修改用户信息成功')
        this.getUserList()
      })
    },
    async deleteUserById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // console.log(confirmResult);
      if (confirmResult === 'cancel') return this.$message.info('已取消操作')
      if (confirmResult == 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.getUserList()
      }
    },
    async settingRole(userInfo) {
      this.settingDialogVisible = true

      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.message.error('访问角色列表失败')
      this.roleList = res.data
      console.log(res.data);
      this.userInfo = userInfo
    },
    async saveRoleInfo(){
      if(!this.selectRoleId) return this.$message.error('请选择一个角色')
      const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleId})
      if(res.meta.status!==200) return this.$message.error('保存角色信息失败')
      this.$message.success('保存角色信息成功')
      this.getUserList()
      this.settingDialogVisible = true
    },
    settingDialogVisibleClosed(){
      this.selectRoleId=''
      this.userInfo={}
    }

  }
}
</script>

<style lang="less" scoped></style>